import React, { useState, useRef } from 'react';
import { Button, Card, Spin, Typography, message, Modal } from 'antd';
import { useAnalysisStore } from '@/stores/analysisStore';
import CodeMirror from '@uiw/react-codemirror';
import { html } from '@codemirror/lang-html';
import { vscodeDark } from '@uiw/codemirror-theme-vscode';
import { SyncOutlined, RocketOutlined } from '@ant-design/icons';
import { AIService } from '../GenerateCode/aiService';
import styles from './index.module.less';

const { Title, Text } = Typography;

const StreamGenerate: React.FC = () => {
  const { analysisResult, setAnalysisResult } = useAnalysisStore();
  const [isLoading, setIsLoading] = useState(false);
  const [generationStatus, setGenerationStatus] = useState('');
  const [tempHtml, setTempHtml] = useState('');
  const editorContainerRef = useRef<HTMLDivElement>(null);

  // 处理滚动到底部
  const scrollToBottom = () => {
    if (editorContainerRef.current) {
      editorContainerRef.current.scrollTop = editorContainerRef.current.scrollHeight;
    }
  };

  // 处理流式更新
  const handleStreamUpdate = (partialResponse: string) => {
    const formattedResponse = partialResponse
      .replace(/\\n/g, '\n')
      .replace(/\[DONE\]/g, '');
    
    if (formattedResponse && !formattedResponse.startsWith('正在处理您的请求...')) {
      setTempHtml(formattedResponse);
      // 每次更新后滚动到底部
      setTimeout(scrollToBottom, 10);
    }
  };

  // 处理生成HTML
  const handleGenerateHtml = async () => {
    setIsLoading(true);
    setGenerationStatus('正在生成HTML...');

    try {
      // 使用第三步的HTML作为输入
      const inputHtml = analysisResult?.html || '';
      
      // 调用AI服务生成HTML
      const prompt = "根据这个HTML代码，优化其结构和样式，使其更符合现代前端开发标准，并添加响应式设计支持。";
      
      const generatedHtml = await AIService.modifyHtml(
        inputHtml,
        prompt,
        handleStreamUpdate
      );

      // 更新store中的streamHtml
      setAnalysisResult({
        ...analysisResult,
        streamHtml: generatedHtml
      });

      // 使用弹窗提示生成完成
      Modal.success({
        title: 'HTML生成成功',
        content: '已成功生成优化的HTML代码',
        okText: '确定'
      });

      setGenerationStatus('');
    } catch (error: any) {
      console.error('生成HTML错误:', error);
      message.error(`生成失败: ${error.message}`);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Card className={styles.container}>
     
        <div className={styles.header}>
            <Button type="primary" onClick={handleGenerateHtml}>生成HTML</Button>
        </div>

        <div className={styles.editorContainer} ref={editorContainerRef}>
          <CodeMirror
            value={isLoading ? tempHtml : (analysisResult?.streamHtml || '')}
            theme={vscodeDark}
            extensions={[html()]}
            readOnly={true}
            basicSetup={{
              lineNumbers: true,
              foldGutter: true,
              highlightActiveLine: true,
            }}
          />
        </div>
    </Card>
  );
};

export default StreamGenerate; 